<!--
* description: 备件价格查询总部
* author: xuliwen
* createdDate: 2021-01-21
-->
<template>
  <div class="app-container app-container-table">
    <one-table-template
      ref="multipleTable"
      :key="oneTableKey"
      :dynamic-buttons="tableButtons"
      :dynamic-components="tableComponents"
      :dynamic-api-config="apiConfig"
      :dynamic-table-cols="tableCols"
      :dynamic-form-fields="formField"
      :dynamic-is-show-select="false"
      :dynamic-is-init-table="true"
      :dynamic-is-show-more-btn="true"
      :dynamic-api-style="'restful'"
      :dynamic-cell-style="columnStyle"
      :callback-obj="callbackObj"
    >
      <template #headquartersProfitMargin="{row}">
        <span>{{ row['headquartersProfitMargin'] | percentage }}</span>
      </template>
      <template #outletProfitMargin="{row}">
        <span>{{ row['outletProfitMargin'] | percentage }}</span>
      </template>
    </one-table-template>
  </div>
</template>
<script>
import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import OneTableTemplate from '@/components/templates/oneTable'
import { exportExcel } from '@/utils/getTimeString.js'
import { orgApis } from '@/api/pabasicdataapi'
import api from '@/api/pa/apiBaseData'
import Vue from 'vue'

export default {
  name: 'PricePartsQueryZB',

  components: {
    OneTableTemplate
  },
  filters: {
    // 小数转换百分比显示
    percentage: function(num) {
      if (!num) return ''
      return (Number(num) * 100).toFixed(2) + '%'
    },
    fixTwo: function(val) {
      return Number(val).toFixed(2)
    }
  },
  // 组件混入对象
  mixins: [oneTableWithViewTemplateMixins],

  // 阻塞路由预加载网格中组件的数据
  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData([to.path, ''], function() {
      next()
    })
  },
  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path

    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])

    return {
      icon: 'el-icon-arrow-down',
      status: false,
      editRowData: {},
      selectiondata: null,
      // 网格查询API配置对象
      apiConfig: api.queryPartPricePageZB,
      columnStyle({ row, column, rowIndex, columnIndex }) {
        if (!row['headquartersProfitMargin']) return ''
        if (!row['outletProfitMargin']) return ''
        // 颜色 红 -- 黄 -- 绿
        const bg = {
          red: 'background:#eb4d4b !important',
          yellow: 'background:#f9ca24 !important',
          green: 'background:#badc58 !important'
        }
        // 低于最低阈值时，标红；不在区间内，但高于最低阈值，标黄；
        function handleProfit({ range: [low, high], min }, value, prop) {
          if (value < min) {
            return bg.red
          } else if (value > min && value < low) {
            return bg.yellow
          } else if (value >= low && value <= high) {
            return bg.green
          } else {
            return bg.yellow
          }
        }
        // dlrProfitMarginH  dlrProfitMarginL  网点利润率区间
        // oemProfitMarginH  oemProfitMarginL  总部利润率区间
        // dlrProfitMarginMin 网点最低利润率
        // oemProfitMarginMin 总部最低利润率
        if (column.property === 'headquartersProfitMargin') {
          return handleProfit({
            range: [row['oemProfitMarginL'], row['oemProfitMarginH']],
            min: row['oemProfitMarginMin']
          }, Number(row['headquartersProfitMargin']), 'headquartersProfitMargin'
          )
        }
        if (column.property === 'outletProfitMargin') {
          return handleProfit({
            range: [row['dlrProfitMarginL'], row['dlrProfitMarginH']],
            min: row['dlrProfitMarginMin']
          }, Number(row['outletProfitMargin']), 'outletProfitMargin'
          )
        }
        // if (column.property === 'prHeadquartersProfitMargin') {
        //   if (!row['prHeadquartersProfitMargin']) return
        //   return handleProfit({
        //       range: [row['oemProfitMarginL'], row['oemProfitMarginH']],
        //       min: row['oemProfitMarginMin']
        //     }, Number(row['prHeadquartersProfitMargin']), 'prHeadquartersProfitMargin'
        //   )
        // }
        // if(row.headquartersProfitMargin&&row.oemProfitMarginMin&&row.oemProfitMarginH&&row.oemProfitMarginL&&row.dlrProfitMarginL&&row.dlrProfitMarginH&&row.dlrProfitMarginMin){
        // if (columnIndex === 8) {
        //   if (
        //     parseFloat(row.headquartersProfitMargin) < row.oemProfitMarginMin
        //   ) {
        //     return 'background:red'
        //   } else if (
        //     (parseFloat(row.headquartersProfitMargin) > row.oemProfitMarginH ||
        //       parseFloat(row.headquartersProfitMargin) <
        //         row.oemProfitMarginL) &&
        //     parseFloat(row.headquartersProfitMargin) > row.oemProfitMarginMin
        //   ) {
        //     return 'background:yellow'
        //   }
        // } else if (columnIndex === 12) {
        //   if (parseFloat(row.outletProfitMargin) < row.dlrProfitMarginMin) {
        //     return 'background:red'
        //   } else if (
        //     (parseFloat(row.outletProfitMargin) > row.dlrProfitMarginH ||
        //       parseFloat(row.outletProfitMargin) < row.dlrProfitMarginL) &&
        //     parseFloat(row.outletProfitMargin) > row.dlrProfitMarginMin
        //   ) {
        //     console.log(
        //       parseFloat(row.outletProfitMargin) > row.dlrProfitMarginH ||
        //         parseFloat(row.outletProfitMargin) < row.dlrProfitMarginL
        //     )
        //     return 'background:yellow'
        //   }
        // }
        // }
      },
      // 动态组件-按钮
      tableButtons: [
        {
          compKey: 'btnKey1',
          type: 'primary',
          size: 'small',
          name: 'search',
          clickEvent: () => this.queryTable(1),
          text: this.$t('sys.button.query'), // 查询
          position: 'right',
          fuzzySearch: true
        },
        {
          compKey: 'btnKey2',
          type: '',
          size: 'small',
          name: 'reset',
          clickEvent: () => this.reset(),
          text: this.$t('sys.button.reset'),
          position: 'right' // 重置
        },
        {
          compKey: 'btnKey3',
          type: '',
          size: 'small',
          clickEvent: () => this.exportExcel111(),
          text: '导出',
          name: 'export',
          position: 'left'
        }
      ],

      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
            .tableComponents
          : [
            {
              compKey: 'compKey6',
              labelName: '备件编码：',
              codeField: 'partNo',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey7',
              labelName: '备件名称：',
              codeField: 'partName',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey1',
              labelName: '维修类型：',
              codeField: 'partRepairType',
              textField: 'partRepairTypeName',
              customObj: {
                api: api.queryPartRepairs
              },
              component: () => import('@/components/org/commonSelect'),
              type: 'dropdownList',
              isMust: true
            },
            {
              compKey: 'compKey2',
              labelName: '备件名称码：',
              codeField: 'partNameCn',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey3',
              labelName: '备件状态：',
              codeField: 'partStatus',
              customObj: {
                api: api.queryPartStatus
              },
              component: () => import('@/components/org/commonSelect'),
              type: 'dropdownList',
              isMul: false,
              isMust: false
            },
            {
              compKey: 'compKey4',
              labelName: '供应商：',
              codeField: 'supplierCode',
              textField: 'supplierShortName',
              component: () => import('@/components/ve/multipleSearchInput'),
              type: 'inputText',
              isMust: false,
              dataToObject: {
                // 控制弹窗页面 搜索 网格 元素
                tableComponents: [
                  {
                    compKey: 'compKey1',
                    labelName: '供应商编码：',
                    codeField: 'supplierCode',
                    component: () => import('@/components/org/commonInput'),
                    type: 'inputText',
                    isMust: true,
                    span: 8
                  },
                  {
                    compKey: 'compKey2',
                    labelName: '供应商简称：',
                    codeField: 'supplierShortName',
                    component: () => import('@/components/org/commonInput'),
                    type: 'inputText',
                    isMust: true,
                    span: 8
                  },
                  {
                    compKey: 'compKey3',
                    labelName: '状态：',
                    codeField: 'isEnable',
                    component: () => import('@/components/org/LookupValue'),
                    oFields: 'statusId,statusText',
                    options: [
                      { statusId: '1', statusText: '启用' },
                      { statusId: '0', statusText: '禁用' }
                    ],
                    type: 'dropdownList',
                    isMust: true,
                    span: 8
                  }
                ],
                tableCols: [
                  {
                    prop: 'supplierCode',
                    label: '供应商编码'
                  },
                  {
                    prop: 'supplierShortName',
                    label: '供应商简称'
                  },
                  {
                    prop: 'supplierFullName',
                    label: '供应商全称'
                  },
                  {
                    prop: 'supplierAddr',
                    label: '详细地址'
                  },
                  {
                    prop: 'linkMan',
                    label: '联系人'
                  },
                  {
                    prop: 'linkManTel',
                    label: '联系电话'
                  },
                  {
                    prop: 'isEnableCn',
                    label: '状态'
                  },
                  {
                    prop: 'remark',
                    label: '备注'
                  }
                ],
                formField: {
                  supplierCode: '',
                  isEnable: '',
                  supplierShortName: ''
                },
                returnField: {
                  prop: 'supplierCode',
                  label: '供应商编码'
                },
                api: orgApis.supplierInformationQueryquery
              },
              span: 6
            },
            {
              compKey: 'compKey8',
              labelName: '适用车型：',
              codeField: 'carConfigCode',
              textField: 'carConfigCn',
              component: () => import('@/views/ve/planReport/components/multipleSearchInput'),
              dataToObject: {
                oFields: 'carConfigCode,carConfigCn',
                // 控制弹窗页面 搜索 网格 元素
                tableComponents: [
                  {
                    compKey: 'compKey1',
                    labelName: '车型编码：',
                    codeField: 'carConfigCode',
                    isMul: false,
                    component: () => import('@/components/org/commonInput'),
                    type: 'inputText',
                    isMust: true,
                    span: 8
                  },
                  {
                    compKey: 'compKey2',
                    labelName: '车型名称：',
                    codeField: 'carConfigCn',
                    isMul: false,
                    component: () => import('@/components/org/commonInput'),
                    type: 'inputText',
                    isMust: true,
                    span: 8
                  }
                ],
                tableCols: [
                  {
                    prop: 'carSeriesCode',
                    label: '车系编码'
                  },
                  {
                    prop: 'carSeriesCn',
                    label: '车系名称'
                  },
                  {
                    prop: 'carConfigCode',
                    label: '车型编码'
                  },
                  {
                    prop: 'carConfigCn',
                    label: '车型名称'
                  }
                ],
                formField: {
                  carConfigCode: '',
                  carConfigCn: ''
                },
                returnField: {
                  prop: 'carConfigCode',
                  label: '车型编码'
                },
                api: { APIUrl: 'mp/e3sh/spareparts/basic/partPriceQueryService/queryCarConfigCodes.do', ServiceCode: 'queryCarConfigCodes' }
              },
              type: 'inputText',
              isMul: false,
              isMust: false
            },
            // {
            //   compKey: 'compKey9',
            //   labelName: '有替代件',
            //   codeField: 'replacePiece',
            //   component: () => import('@/components/org/LookupValue'),
            //   oFields: 'statusId,statusText',
            //   options: [
            //     { statusId: '1', statusText: '是' },
            //     { statusId: '0', statusText: '否' }
            //   ],
            //   type: 'dropdownList',
            //   isMul: false,
            //   isMust: false
            // }
            //   {
            //   compKey: 'compKey10',
            //   span: 24,
            //   codeField: 'orderStatus',
            //   isMul: true,
            //   component: () => import('@/components/org/checkBox/pa_checkGroup.vue'),
            //   type: '',
            //   isMust: false
            // }
          ],

      // 动态生成网格列
      tableCols:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          : [
            {
              prop: 'partId',
              label: '备件ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'partPriceId',
              label: '备件价格ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'updateControlId',
              label: '并发ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'isEnable',
              label: '是否启用',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'partNo',
              label: '备件编码'
            },
            {
              prop: 'partName',
              label: '备件名称',
              width: 110
            },
            {
              prop: 'purchasePrice',
              label: '采购价',
              hidden:true
            },
            {
              prop: 'costPrice',
              label: '标准成本价'
            },
            // {
            //   prop: 'pointPriceTax',
            //   label: '正常订单价含税',
            //   width: 115
            // },
            {
              prop: 'pointPriceNotTax',
              label: '正常订单价',
              width: 115
            },
            {
              prop: 'urgentOrderPriceNotTax',
              label: '紧急订单价'
            },
            {
              prop: 'userPrice',
              label: '建议零售价'
            },
            {
              prop: 'outletProfitMargin',
              label: '正常订单利润率',
              isSlot: true
            }, 
            {
              prop: 'headquartersProfitMargin',
              label: '总部利润率',
              isSlot: true
            },            
            {
              prop: 'pointEffectiveDate',
              label: '正常订单价生效日期',
              width: 127,
              hidden:true
            },            
            {
              prop: 'outletProfitMargin',
              label: '网点利润率',
              isSlot: true,
              hidden:true
            },
            {
              prop: 'userEffectiveDate',
              label: '建议零售价生效日期',
              width: 127,
              hidden:true
            },
            {
              prop: 'partRepairTypeName',
              label: '维修类型'
            },
            {
              prop: 'carConfigIdList',
              label: '适用车型',
              width: '150px',
              hidden:false
            },
            {
              prop: 'partNameId',
              label: '备件名称码'
            },
            {
              prop: 'partStatus',
              label: '备件状态'
            }
          ],
      callbackObj: {
        // 手动勾选时
        onCheckSelect: (selection, row) => {
          this.selectiondata = selection
        },
        onCheckSelectChange: (selection) => {
          this.onCheckSelectChange1(selection)
        }
      },
      // 表单查询数据
      formField: this.$utils.getFormField(
        this,
        {
          partRepairType: '',
          partNameCn: '',
          partStatus: '',
          supplierCode: '',
          partNo: '',
          partName: '',
          carConfigIdList: '',
          replacePiece: '',
          carConfigCode: '',
          carConfigCn: ''
        },
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode]
      )
    }
  },
  watch: {
    'formField.carConfigCn': {
      deep: true,
      handler: function(newV, oldV) {
        if (newV == '' || newV == null) {
          this.formField.carConfigIdList = ''
        }
      }
    }
  },
  mounted() {
    // 列表查询
    this.queryTable(1)
  },

  methods: {
    exportExcel111() {
      exportExcel(
        this.formField,
        api.queryPartPriceExport.APIUrl,
        api.queryPartPriceExport.ServiceCode,
        '备件价格查询总部'
      )
    }
  }
}
</script>
<style lang='scss' scoped>
</style>
